package com.seal.dao.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.seal.comm.utils.Page;
import com.seal.dao.BaseDaoImpl;
import com.seal.dao.IAdvDao;
import com.seal.dto.AdvDto;
import com.seal.model.Adv;

@Repository("advDaoImpl")
@SuppressWarnings("unchecked")
public class AdvDaoImpl extends BaseDaoImpl implements IAdvDao {

	public void addAdv(Adv ca) throws Exception {
		this.save(ca);
	}

	public void updateAdv(Adv ca) throws Exception {
		this.update(ca);
	}

	public void deleteAdv(Adv ca) throws Exception {
		this.delete(ca);
	}

	public Adv getAdvById(Long id) throws Exception {
		return (Adv) this.select(Adv.class, id);
	}

	public List<Adv> getAdvList(AdvDto dto, Page page) throws Exception {
		StringBuffer hql = new StringBuffer("from Adv t where 1=1");
		if (null != dto.getFromDate()) {
			hql.append(" and t.startDate <= :fromDate");
		}

		if (null != dto.getToDate()) {
			hql.append(" and t.endDate >= :toDate");
		}

		if (null != dto.getStatus()) {
			hql.append(" and t.status = :status");
		}

		if (!StringUtils.isEmpty(dto.getAdvName())) {
			hql.append(" and t.advName = :advName");
		}

		Query query = this.getSession().createQuery(hql.toString());
		query.setProperties(dto);
		if (null != page) {
			query.setFirstResult(page.getFirstResult());
			query.setMaxResults(page.getPageSize());
			String countSql = "select count(t) " + hql.toString();

			Query queryCount = this.getSession().createQuery(countSql);
			queryCount.setProperties(dto);
			page.setTotalNumber(Integer.parseInt(queryCount.uniqueResult().toString()));
		}

		return query.list();
	}

}
